package Realchat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Receive implements  Runnable {
      DatagramSocket socket=null;
      private  int port;
      private String msgFrom;

    public Receive(int port,String msgFrom){       //开启连接
        this.port=port;
        this.msgFrom=msgFrom;
        try { socket=new DatagramSocket(port);

        }catch (SocketException e){
        e.printStackTrace();
        }
   }
    @Override
    public void run() {
        while(true){
            try{  //准备接受包裹
                byte[] container=new byte[1024];
                DatagramPacket packet=new DatagramPacket(container,0,container.length);
                socket.receive(packet);//阻塞式接收包裹

                //断开连接 bye
                byte[] data1= packet.getData();
                String ReceieveData=new String(data1,0,data1.length);
                System.out.println(msgFrom+":"+ReceieveData);

                if(ReceieveData.equals("bye")){
                    break;
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
